// npm i ejs 
// npm i express
// npm i mysql
// npm i body-parser
const fs = require('fs')
const path = require('path')
const ejs = require('ejs')
const express = require('express')
const mysql = require('mysql')
const bodyParser = require('body-parser')

// 创建服务器
const app = express()

// 使用body-parser中间件
app.use(bodyParser.urlencoded({ extended: false }))

// 连接数据  
const client = mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    // 你的mysql的密码
    password: '123456',
    // 你的数据库的名称
    database: 'book'
})

// 测试是否连接成功
client.connect((err) => {
    if (err) {
        console.log('【连接失败】' + err)
        return
    }
    console.log('【连接成功】')
})


// 图书显示
const fpath = path.join(__dirname, './book-list.html')
app.get('/', (req, res) => {
    fs.readFile(fpath, 'utf8', (err, data) => {
        // test 你的数据库里面的表的名称
        client.query('select * from test', (err, result) => {
            res.send(ejs.render(data, {
                data: result
            }))
        })
    })
})

// 添加数据
const fpath2 = path.join(__dirname, './book-insert.html')
app.get('/insert', (req, res) => {
    // fs.readFile(fpath2, 'utf8', (err, data) => {
    //     res.send(data)
    // })
    res.sendFile(fpath2)
})

app.post('/insert', (req, res) => {
    const body = req.body
    console.log(body)
    client.query('insert into test (bookname,author,press) values (?,?,?)', [body.bookname, body.author, body.press], () => {
        res.redirect('/')
    })
})

//删除
app.get('/delete/:id', (req, res) => {
client.query('delete from test where id=?', [req.params.id], () => {
    res.redirect('/')
})
})

//编辑
const fpath3 = path.join(__dirname, './book-edit.html')
app.get('edit/:id', (req,res) => {
    // res.send('100')
    fs.readFile(fpath3, 'utf8', (err, data) => {
        client.query('select * from test where id=?', [req.
            params.id],(err,result) => {
                res.send(ejs.render(data, {
                    data: result[0]
                }))
            })
    })
})

app.post('/edit:id', (req, res) => {
})



app.listen(3000, (req, res) => {
    console.log('http://127.0.0.1:3000')
})